package com.cctc.mychat.common.session;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;

import java.util.HashMap;
import java.util.Map;

public class SessionManager {
    private static final Map<String, Channel> SESSION_MAP = new HashMap<>();

    public static final void bindSession(Session session, Channel channel) {
        SESSION_MAP.put(session.getUserName(), channel);
        channel.attr(Attributes.SESSION).set(session);
    }

    public static final void unBindSession(Channel channel) {
        if (hasLogin(channel)) {
            Session session = getSession(channel);
            SESSION_MAP.remove(session.getUserName());
            channel.attr(Attributes.SESSION).set(null);
        }
    }

    public static final boolean hasLogin(Channel channel) {
        return getSession(channel) != null;
    }

    public static final Session getSession(Channel channel) {
        return channel.attr(Attributes.SESSION).get();
    }

    public static final Channel getChannel(String userName) {
        return SESSION_MAP.get(userName);
    }

}
